import React, { useState, useMemo, useEffect} from 'react';
import { Modal, Form, Input, Button, Table, Checkbox, Tag } from 'antd';

const { TextArea } = Input;

interface TableItem {
  name: string;
  comment: string;
}

interface TableSetModalProps {
  open: boolean;
  onCancel: () => void;
  onOk: (values: any) => void;
  dbName: string;
  tableList: TableItem[];
  defaultSelected?: string[];
}

const TableSetModal: React.FC<TableSetModalProps> = ({
  open,
  onCancel,
  onOk,
  dbName,
  tableList,
  defaultSelected = [],
}) => {
  const [form] = Form.useForm();
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>(defaultSelected);
  const [search, setSearch] = useState('');

  // 搜索过滤
  const filteredTableList = useMemo(
    () =>
      tableList.filter(
        t =>
          t.name.toLowerCase().includes(search.toLowerCase()) ||
          t.comment.toLowerCase().includes(search.toLowerCase())
      ),
    [search, tableList]
  );

  // 表格列
  const columns = [
    {
      title: '表名',
      dataIndex: 'name',
      key: 'name',
      width: 160,
      render: (text: string) => <span className="font-semibold">{text}</span>,
    },
    {
      title: '表注释',
      dataIndex: 'comment',
      key: 'comment',
      render: (text: string) => <span>{text}</span>,
    },
  ];

  // 多选配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (keys: React.Key[]) => setSelectedRowKeys(keys as string[]),
  };

  // 全选/取消全选
  const handleSelectAll = () => setSelectedRowKeys(filteredTableList.map(t => t.name));
  const handleClearAll = () => setSelectedRowKeys([]);

  // 提交
  const handleOk = async () => {
    const values = await form.validateFields();
    onOk({ ...values, tables: selectedRowKeys });
  };

  return (
    <Modal
      open={open}
      title="构建表集合"
      onCancel={onCancel}
      onOk={handleOk}
      width={800}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          取消
        </Button>,
        <Button key="ok" type="primary" onClick={handleOk} disabled={selectedRowKeys.length === 0}>
          确定
        </Button>,
      ]}
    >
      <div className="flex gap-4">
        {/* 左侧表单 */}
        <div className="flex-1">
          <Form form={form} layout="vertical">
            <Form.Item
              label="表集合名称"
              name="name"
              rules={[{ required: true, message: '请输入表集合名称' }]}
            >
              <Input placeholder="请输入" />
            </Form.Item>
            <Form.Item
              label="表集合描述"
              name="desc"
              rules={[{ required: true, message: '请输入描述内容' }]}
            >
              <TextArea placeholder="请输入描述内容" maxLength={200} showCount rows={4} />
            </Form.Item>
            <Form.Item label="所属数据源" required>
              <Tag color="purple" className="px-4 py-2 text-base">{dbName}</Tag>
            </Form.Item>
          </Form>
        </div>
        {/* 右侧表格 */}
        <div className="w-[380px] bg-[#fafbfc] rounded-lg border p-4">
          <div className="flex justify-between items-center mb-2">
            <span>
              已选择
              <Tag color="blue" className="mx-1">{selectedRowKeys.length}</Tag>
              个表
            </span>
            <div>
              <a onClick={handleSelectAll}>全选</a>
              <span className="mx-1">/</span>
              <a onClick={handleClearAll}>取消全选</a>
            </div>
          </div>
          <Input
            placeholder="搜索表名"
            allowClear
            size="small"
            className="mb-2"
            value={search}
            onChange={e => setSearch(e.target.value)}
          />
          <Table
            rowKey="name"
            size="small"
            columns={columns}
            dataSource={filteredTableList}
            rowSelection={{
              type: 'checkbox',
              ...rowSelection,
            }}
            pagination={false}
            scroll={{ y: 260 }}
          />
        </div>
      </div>
    </Modal>
  );
};

export default TableSetModal;